package com.wind.oauth2.server.config.service;

import com.wind.oauth2.server.entity.TbPermission;
import com.wind.oauth2.server.entity.TbUser;
import com.wind.oauth2.server.service.TbPermissionService;
import com.wind.oauth2.server.service.TbUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private TbUserService tbUserService;
    //将操作 授权  取出来 给 oauth2进行操作
    @Autowired
    private TbPermissionService tbPermissionService;



    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbUser tbUser = tbUserService.getByUsername(username);
        //授权  给框架放权限
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (tbUser != null){
            //查询出  权限
            List<TbPermission> permissions = tbPermissionService.getPermissionByUserId(tbUser.getId());
            permissions.forEach(permission ->{
                GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getEnname());
                grantedAuthorities.add(grantedAuthority);
            });
        }

        return new User(tbUser.getUsername(),tbUser.getPassword(),grantedAuthorities);
    }
}
